import 'dart:io';

import 'package:find_friend/const/const.dart';
import 'package:find_friend/pages/login&register/model/shared_user_info.dart';
import 'package:find_friend/pages/mine/mine_photos_wall.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:rongcloud_im_plugin/rongcloud_im_plugin.dart';
import 'package:transparent_image/transparent_image.dart';

class MsgImageHistoryPage extends StatefulWidget {

  final String mobile;

  const MsgImageHistoryPage({Key key, this.mobile}) : super(key: key);

  @override
  _MsgImageHistoryPageState createState() => _MsgImageHistoryPageState();
}

class _MsgImageHistoryPageState extends State<MsgImageHistoryPage> {

  Map<String, dynamic> source = {};
  List<String> sourceKey = [];
  static const String heroPerfix = "msghistory";
  @override
  void initState() {
    super.initState();

    onGetHistoryMessages(widget.mobile);

    SharedUserInfo.instance().then((value) => onGetHistoryMessages(value.mobile));
  }

  onGetHistoryMessages(String userid) async {
    List msgs = await RongcloudImPlugin.getHistoryMessage(RCConversationType.Private, userid, 0, 100);
    print("get history message");
    for(Message m in msgs) {
      if (m.content is ImageMessage) {
        ImageMessage msg = m.content;
        String date = DateTime.fromMillisecondsSinceEpoch(m.sentTime).month.toString();
        List<String> temp = source[date];
        if(temp == null) {
          temp = [msg.imageUri];
          source[date] = temp;
        } else {
          temp.add(msg.imageUri);
          source[date] = temp;
        }
      }
    }

    
    setState(() {
      sourceKey = source.keys.toList();  
      sourceKey.sort();
    });

    print(source);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: APP_scaffold_back_color,
      appBar: AppBar(
        title: Text("聊天图片"),
        backgroundColor: Colors.white,
        centerTitle: true,
        leading: IconButton(
          onPressed: (){
            Navigator.of(context).pop();
          },
          icon: Image.asset("assets/fanhui.png"),
        ),
      ),
      body: ListView.builder(
        padding: const EdgeInsets.all(10),
        itemCount: sourceKey.length,
        itemBuilder: (context, index){
          List list = source[sourceKey[index]];
          return Container(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text("${sourceKey[index]}月", style: instanceTextStyle(9, APP_font_grey),),
                GridView.builder(
                  padding: const EdgeInsets.symmetric(vertical: 6),
                  shrinkWrap: true,
                  itemCount: list.length,
                  physics: NeverScrollableScrollPhysics(),
                  gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                    crossAxisCount: 5,
                    mainAxisSpacing: 5,
                    crossAxisSpacing: 5,
                  ),
                  itemBuilder: (context, index2) {
                    return GestureDetector(
                      onTap: (){
                        Navigator.push(context, PageRouteBuilder(
                                pageBuilder: (BuildContext context, Animation animation,
                                    Animation secondaryAnimation) {
                                  List<FileModel> temp = list.map((e) => FileModel(url: e, id:index2)).toList();
                                  return new FadeTransition(
                                    opacity: animation,
                                    child: MinePhotoWallPage(heroTag: heroPerfix + index2.toString(), list: temp,),
                                  );
                                })
                            );
                      },
                      child: PhysicalModel(
                        color: Colors.transparent,
                        borderRadius: BorderRadius.circular(10),
                        clipBehavior: Clip.antiAlias,
                        child: Hero(
                          tag: heroPerfix + index2.toString(),
                          child: FadeInImage.memoryNetwork(
                              placeholder: kTransparentImage,
                              image: list[index2] ?? "",
                              fit: BoxFit.cover,
                            )
                        ),
                      ),
                    );
                  },
                )
              ],
            ),
          );
        }
      ),
    );
  }
}